import type { VNode } from 'vue'
import type { DirectiveBinding } from 'vue/types/options'

/*
 * @Author: 黄威
 * @Date: 2021-11-11 10:17:21
 * @LastEditors: 黄威
 * @LastEditTime: 2021-11-11 11:24:51
 * @Description: 基础拖动命令插件
 */
export default {
    inserted(el: HTMLElement, binding: DirectiveBinding, vnode: VNode) {
        const target = el.querySelector(binding.arg || 'header')
        if (!target) return

        const title = target as HTMLElement
        el.style.willChange = 'top, left'
        title.style.cursor = 'move'

        // 拖动相关事件
        let x = 0
        let y = 0
        function mousedownHandler(evt: MouseEvent) {
            // 还原状态先
            mouseupHandler()

            x = evt.x
            y = evt.y
            document.addEventListener('mousemove', mousemoveHandler)
            document.addEventListener('mouseup', mouseupHandler)
        }
        function mousemoveHandler(evt: MouseEvent) {
            /* 
            // 视图范围
            const dragDomWidth = el.offsetWidth
            const dragDomheight = el.offsetHeight

            const screenWidth = document.body.clientWidth
            const screenHeight = document.body.clientHeight

            const minDragDomLeft = el.offsetLeft
            const maxDragDomLeft = screenWidth - el.offsetLeft - dragDomWidth

            const minDragDomTop = el.offsetTop
            const maxDragDomTop = screenHeight - el.offsetTop - dragDomheight
            */
            // 更新相关视图

            const offsetX = evt.x - x
            const offsetY = evt.y - y

            el.style.left = el.offsetLeft + offsetX + 'px'
            el.style.top = el.offsetTop + offsetY + 'px'

            // 更新上次坐标位置
            x = evt.x
            y = evt.y

            evt.preventDefault()
            evt.stopPropagation()
        }
        function mouseupHandler() {
            document.removeEventListener('mousemove', mousemoveHandler)
            document.removeEventListener('mouseup', mouseupHandler)
        }

        // 绑定title事件
        title.addEventListener('mousedown', mousedownHandler)
    },
}
